package cn.wolfcode.web.advice;

import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.exception.BusinessException;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class ExceptionControllerAdvice {
    @ExceptionHandler(BusinessException.class)
    public void handleException(BusinessException e, HttpServletResponse response, HandlerMethod method) throws IOException {
        e.printStackTrace();
        ResponseBody annotation = method.getMethodAnnotation(ResponseBody.class);
        if (annotation==null){
            response.sendRedirect("/error");
        }else{
            //设置返回的编码方式,因为有中文所以要设置成utf-8
            response.setContentType("application/json;charset=utf-8");
            //因为是阿贾克斯请求所以要返回json字符串
            String data = JSON.toJSONString(new JsonResult(false, e.getMessage()));
            response.getWriter().write(data);
        }



    }
    //只要有异常就再这里处理掉
@ExceptionHandler(Exception.class)
    public void handleException(Exception e, HttpServletResponse response, HandlerMethod method) throws IOException {
    e.printStackTrace();
        ResponseBody annotation=method.getMethodAnnotation(ResponseBody.class);
    if (annotation==null){
        response.sendRedirect("/error");
    }else{
        //设置返回的编码方式,因为有中文所以要设置成utf-8
        response.setContentType("application/json;charset=utf-8");
        //因为是阿贾克斯请求所以要返回json字符串
        String data = JSON.toJSONString(new JsonResult(false, "系统出现异常,请联系管理员"));
        response.getWriter().write(data);
    }



    }
}
